import { useCallback, useEffect, useState } from "react";
import { getQRCodeInfoById } from "../api";
import { IQRCode } from "../types";

type TUseQRCodeInfo = (
  id: string
) => [loading: boolean, QRCode: IQRCode, error: boolean];

const useQRCodeInfo: TUseQRCodeInfo = (id) => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const [QRCode, setQRCode] = useState({});

  const getQRCodeInfo = useCallback(() => {
    setLoading(true);
    getQRCodeInfoById(id)
      .then((res) => {
        console.log("res", res);
        setQRCode(res);
      })
      .catch((err) => {
        console.error("err", err);
        setError(true);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [id]);

  useEffect(() => {
    getQRCodeInfo();
  }, [getQRCodeInfo]);

  return [loading, QRCode, error];
};

export default useQRCodeInfo;
